package com.algorithm.thePrimaryAlgorithm;

import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

@Slf4j
public class StringSulotionLC20 {
    public String longestCommonPrefix(String[] strs) {
        // 1 找到长度最小的str
        String minStr = strs[0];
        for (int i = 1; i < strs.length; i++) {
            if (strs[i].length() < minStr.length()) {
                minStr = strs[i];
            }
        }
        // 循环获取公共前缀 拼接
        String result = "";
        for (int i = 0; i < minStr.length(); i++) {
            char c = minStr.charAt(i);
            for (int j = 0; j < strs.length; j++) {
                if (strs[j].charAt(i) != c) {
                    return result;
                }
            }
            result = result + c;
        }
        return result;
    }

    @Test
    public void test(){
        String[] strs = {"flower","flow","flight"};
        String s = longestCommonPrefix(strs);
        log.info("over {}",s);
    }


    public String longestCommonPrefix1(String[] strs) {
        String result = strs[0];
        int i = 1;
        while (i < strs.length) {
            int j = 0;
            String temp = "";
            while (j < result.length() && j < strs[i].length()) {
                if (strs[i].charAt(j) == result.charAt(j)) {
                    temp = temp + result.charAt(j);
                } else {
                    break;
                }
                j++;
            }
            result = temp;
            i++;
        }

        return result;
    }

    @Test
    public void test1(){
        String[] strs = {"flower","flow","flight"};
        String s = longestCommonPrefix1(strs);
        log.info("over {}",s);
    }
}
